from flask import jsonify
from flask.views import MethodView
from ..auth import auth_required
from flask_login import current_user
from app.forms.user import UserRegisterForm, UserUpdateForm
from app.models.user import User
from app.extensions import db
from ..forms import ValidateCodeForm, CodeForm, RestPassowrdForm
import requests
import json


class UserAPI(MethodView):
    decorators = [auth_required]

    def get(self):
        data = current_user.to_dict()
        return jsonify(success=True, data=data)

    def post(self):
        form = UserUpdateForm()
        if form.validate_on_submit:

            username = form.username.data
            password = form.password.data

            user_res = requests.get('http://user.apiary.com.cn/v1/user/authorize?login={}&password={}'.format(username, password))
            data = json.loads(user_res.text)
            if data['success'] is False:
                return jsonify(success=False, message=data['data']['message'])

            headers = {'Authorization': 'Bearer {}'.format(data['data']['access_token'])}

            res = requests.patch('http://user.apiary.com.cn/v1/user/password', data={'password': form.new_password.data}, headers=headers)
            res_data = json.loads(res.text)

            if res_data['success'] is False:
                return jsonify(success=False, message=res_data['data']['message'])

            return jsonify(success=True, data=res_data)


# 注册用户
class UsersAPI(MethodView):
    # 注册账号
    def post(self):
        form = UserRegisterForm()

        if form.validate_on_submit:
            data = {
                'username': form.username.data,
                'password': form.password.data,
                'code': form.code.data
            }

            res = requests.post('http://user.apiary.com.cn/v1/user', data=data)
            res_data = json.loads(res.text)
            if res_data['success'] is False:
                return jsonify(success=False, message=res_data['data']['message'])

            user = User.query.filter_by(username=form.username.data).first()

            if user is None:
                user = User(username=form.username.data, status=100)
                db.session.add(user)
                db.session.commit()

            return jsonify(success=True, data=res_data)

    # 重置密码
    def put(self):
        form = RestPassowrdForm()

        if form.validate_on_submit:
            data = {
                'tel': form.tel.data,
                'code': form.code.data,
                'password': form.password.data
            }
            res = requests.patch('http://user.apiary.com.cn/v1/user/reset', data=data)
            res_data = json.loads(res.text)
            if res_data['success'] is False:
                return jsonify(success=False, message=res_data['data']['message'])

            return jsonify(success=True, data=res_data)


# 阿里验证码
class SmsAPI(MethodView):
    # 获取注册用户验证码
    def post(self):
        form = CodeForm()
        if form.validate_on_submit():
            res = requests.get('http://user.apiary.com.cn/v1/user/sms-code?tel={}&allowCode=wxls'.format(form.tel.data))
            return json.loads(res.text)

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)

    # 获取重置密码验证码
    def put(self):
        form = CodeForm()
        if form.validate_on_submit():
            res = requests.get('http://user.apiary.com.cn/v1/user/sms-code?tel={}&template=SMS_137875022&allowCode=wxls'.format(form.tel.data))
            return json.loads(res.text)

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)
